//
//  FootPrintViewController.m
//  FootPrint
//
//  Created by alex tao on 2/25/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import "FootPrintViewController.h"
#import "EventDetailViewController.h"
#import "EventListCell.h"
#import "UserGridCell.h"
#import "PushMsgCell.h"
#import "NVSimpleWebViewController.h"
#import "FriendDetailViewController.h"
#import "PIODetailViewController.h"

@interface FootPrintViewController ()

@end

@implementation FootPrintViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        _parser = [[EventListParser alloc] init];
        _parser.delegate = self;
        
        _pushParser = [[PushParser alloc]init];
        _pushParser.delegate = self;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _pushGridView.gridDelegate = self;
    _pushGridView.oneRowMode = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendRequest) name:NOTIFY_LOGIN_SUCCESS object:nil];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self sendRequest];
}


- (void)sendRequest{

    // update event
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    
    long long year = [dateComponent year];
    long long month = [dateComponent month];
    long long day = [dateComponent day];
    
    long long beginTime = (year*10000 + month*100 + day) * 1000000;
    long long endTime = beginTime + 235959;
    
    [_parser quaryEventByUser:[GConfig getUserId] beginDate:beginTime endDate:endTime andFilter:@"0000"];
    
    
    // update push
    NSUserDefaults* data = [NSUserDefaults standardUserDefaults];
    NSMutableArray* arr = [data objectForKey:@"pushSetting"];
    if(arr == nil){
        arr = [NSMutableArray arrayWithObjects:[NSNumber numberWithBool:YES], [NSNumber numberWithBool:YES], [NSNumber numberWithBool:YES], [NSNumber numberWithBool:YES], [NSNumber numberWithBool:YES], [NSNumber numberWithBool:YES], nil];
        [data setObject:arr forKey:@"pushSetting"];
    }
    
    BOOL isPeople = [((NSNumber*)[arr objectAtIndex:0])boolValue ];
    BOOL isAddr = [((NSNumber*)[arr objectAtIndex:1])boolValue ];
    BOOL isTime = [((NSNumber*)[arr objectAtIndex:2])boolValue ];
    BOOL isWeather = [((NSNumber*)[arr objectAtIndex:3])boolValue ];
    BOOL isMerchant = [((NSNumber*)[arr objectAtIndex:4])boolValue ];
    BOOL isNew = [((NSNumber*)[arr objectAtIndex:5])boolValue ];
    
    NSString* strFilter = @"1111";
    if(isPeople || isAddr || isTime){
        int filter = 1000;
        if(isTime){
            filter += 100;
        }
        if(isAddr){
            filter += 10;
        }
        if(isPeople){
            filter += 1;
        }
        strFilter = [NSString stringWithFormat:@"%d", filter];
    }
    
    [_pushParser reqPush:[GConfig getUserId] isNews:isNew isShopActivity:isMerchant isWeather:isWeather filter:strFilter];
    
}

- (void)dealloc
{
    self.pushMsgList = nil;
    self.eventList = nil;
    [_parser release];
    [_eventTable release];
    [_pushGridView release];
    [super dealloc];
}


#pragma mark - EventListDelegate

- (void) didRecieveEventList:(EventQueryResponseMessage*)event beginDate:(long long)bgDate endDate:(long long)edDate withFilter:(NSString *)filter
{
    if (event && event.resultCode == 0) {
        self.eventList = event;
        [_eventTable reloadData];
    }
}
- (void)didFinishPush:(NSArray*)resp
{
    self.pushMsgList = resp;
    
    NSMutableArray * userViews = [[[NSMutableArray alloc] initWithCapacity:8] autorelease];
    
    for (NSDictionary * msg in resp)
    {
        PushMsgCell * cell = [[[PushMsgCell alloc] initWithFrame:CGRectMake(0, 0, 80, 80)] autorelease];
        
        NSString * type = [msg objectForKey:@"type"];
        if ([type isEqualToString:@"event"])
        {
            cell.msgLabel.text = [msg objectForKey:@"eventName"];
            NSString * imgUrl = [msg objectForKey:@"imgUrl"];
            if ([imgUrl hasPrefix:@"sys_"]) {
                [cell.msgIcon setLocalImageName:imgUrl];
            } else {
                if ([imgUrl hasPrefix:@"/"] && [imgUrl pathComponents].count>3) {
                    [cell.msgIcon setLocalImageName:imgUrl];
                } else {
                    [cell.msgIcon loadAsyncImage:imgUrl];
                }
            }
        }
        else if ([type isEqualToString:@"invite"])
        {
            cell.msgLabel.text = [msg objectForKey:@"nickName"];
            BOOL isSys = [[msg objectForKey:@"isSys"] boolValue];
            if (!isSys) {
                [cell.msgIcon loadAsyncImage:[msg objectForKey:@"imgUrl"]];
            } else {
                [cell.msgIcon setSysImageWithId:[[msg objectForKey:@"imgId"] longLongValue]];
            }
        }
        else if ([type isEqualToString:@"merchant"])
        {
            cell.msgLabel.text = [msg objectForKey:@"merchantName"];
            BOOL isSys = [[msg objectForKey:@"isSys"] boolValue];
            if (!isSys) {
                [cell.msgIcon loadAsyncImage:[msg objectForKey:@"imgUrl"]];
            } else {
                [cell.msgIcon setSysImageWithId:[[msg objectForKey:@"imgId"] longLongValue]];
            }
        }
        else if ([type isEqualToString:@"url"])
        {
            cell.msgLabel.text = [msg objectForKey:@"title"];
            NSString * imgUrl = [msg objectForKey:@"imgUrl"];
            if ([imgUrl hasPrefix:@"sys_"]) {
                [cell.msgIcon setLocalImageName:imgUrl];
            } else {
                [cell.msgIcon loadAsyncImage:imgUrl];
            }
        }
        
        [userViews addObject:cell];
    }
    
    _pushGridView.cells = userViews;

    //把这些数据添加到本地缓存，并刷新tableView
    //事件显示事件图片+事件名称，好友显示好头头相+好友名称
    //商户显示商户图片+商户名，URL显示urlImg+urlTitle

}

- (void)failPush{
    [[[iToast makeText:@"获取推送信息失败"]setDuration:2000]show];
}




#pragma mark - GridScrollDelegate

- (void) didSelect:(GridScrollView *)gridScroll atTotalIndex :(NSInteger)idx
{
    if (idx < self.pushMsgList.count) {
        NSDictionary * selDic = [self.pushMsgList objectAtIndex:idx];
        NSLog(@"%@", selDic);
        
        NSString * type = [selDic objectForKey:@"type"];
        if([type isEqualToString:@"url"])
        {
            NSString* url = [selDic objectForKey:@"url"];
            NSString* title = [selDic objectForKey:@"title"];
            NVSimpleWebViewController* userVC = [[[NVSimpleWebViewController alloc] init] autorelease];
            userVC.url = [NSURL URLWithString:url];
            userVC.title = title;
            userVC.rawData = selDic;
            
            UINavigationController * navVc = [[[UINavigationController alloc] initWithRootViewController:userVC] autorelease];
            navVc.navigationBarHidden = YES;
            [ROOT_VC presentModalViewController:navVc animated:YES];
        }
        else if ([type isEqualToString:@"event"])
        {
            long long eventId = [[selDic objectForKey:@"eventId"] longLongValue];
            
            if (eventId > 0) {
                EventDetailViewController * detail = [[[EventDetailViewController alloc] initWithNibName:@"EventDetailViewController" bundle:nil] autorelease];
                UINavigationController * navVc = [[[UINavigationController alloc] initWithRootViewController:detail] autorelease];
                navVc.navigationBarHidden = YES;
                [ROOT_VC presentModalViewController:navVc animated:YES];
                
                [detail requestById:eventId];
            } else {
                [[iToast makeText:@"该事件不存在!"] show];
            }
        }
        else if([type isEqualToString:@"invite"])
        {
            long long uid = [[selDic objectForKey:@"userId"] longLongValue];
            
            ImageMessage * imgMsg = [[[[[ImageMessage builder] setId:[[selDic objectForKey:@"imgId"] longLongValue]] setIsSys:[[selDic objectForKey:@"isSys"] boolValue]] setImageUrl:[selDic objectForKey:@"imgUrl"]] build];
            UserMessage * user = [[[[[[UserMessage builder] setId:uid] setNickName:[selDic objectForKey:@"nickName"]] setPortrait:imgMsg] setPhone:@""] build];
            
            FriendDetailViewController * detail = [[[FriendDetailViewController alloc] initWithNibName:@"FriendDetailViewController" bundle:nil] autorelease];
            UINavigationController * navVc = self.navigationController;
            if (nil == navVc) {
                navVc = [[[UINavigationController alloc] initWithRootViewController:detail] autorelease];
                navVc.navigationBarHidden = YES;
                [ROOT_VC presentModalViewController:navVc animated:YES];
            } else {
                [navVc pushViewController:detail animated:YES];
            }
            detail.activityBtn.hidden = YES;
            [detail updateUserStatus:user];
            [detail setRawData:selDic];
        }
        else if([type isEqualToString:@"merchant"])
        {
            long long merchantId = [[selDic objectForKey:@"merchantId"] longLongValue];
            
            ImageMessage * imgMsg = [[[[[ImageMessage builder] setId:[[selDic objectForKey:@"imgId"] longLongValue]] setIsSys:[[selDic objectForKey:@"isSys"] boolValue]] setImageUrl:[selDic objectForKey:@"imgUrl"]] build];
            MerchantMessage * mer = [[[[[MerchantMessage builder] setId:merchantId] setName:[selDic objectForKey:@"merchantName"]] setLogo:imgMsg] build];
            
            PIODetailViewController * poiVC = [[[PIODetailViewController alloc] initWithNibName:@"PIODetailViewController" bundle:nil] autorelease];
            UINavigationController * navVc = self.navigationController;
            if (nil == navVc) {
                navVc = [[[UINavigationController alloc] initWithRootViewController:poiVC] autorelease];
                navVc.navigationBarHidden = YES;
                [ROOT_VC presentModalViewController:navVc animated:YES];
            } else {
                [navVc pushViewController:poiVC animated:YES];
            }
            [poiVC updatePOIInfo:mer];
            poiVC.rawData = selDic;
        }
    }

}


#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.eventList eventSumList].count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *eventCellIdentifier = @"eventCellIdentifier";
    EventListCell *cell = [tableView dequeueReusableCellWithIdentifier:eventCellIdentifier];
    if (cell == nil) {
        cell = [[[EventListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:eventCellIdentifier] autorelease];
    }
    
    NSInteger idx = [self.eventList eventSumList].count - 1 - indexPath.row;
    [cell updateWithEventInfo:[self.eventList eventSumListAtIndex:idx]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    EventDetailViewController * detail = [[[EventDetailViewController alloc] initWithNibName:@"EventDetailViewController" bundle:nil] autorelease];
    UINavigationController * navVc = [[[UINavigationController alloc] initWithRootViewController:detail] autorelease];
    navVc.navigationBarHidden = YES;
    [ROOT_VC presentModalViewController:navVc animated:YES];
    
    NSInteger idx = [self.eventList eventSumList].count - 1 - indexPath.row;
    [detail requestById:[self.eventList eventSumListAtIndex:idx].eventId];
}


- (void)viewDidUnload {
    [self setEventTable:nil];
    [self setPushGridView:nil];
    [super viewDidUnload];
}

- (IBAction)createEvent
{
    EventDetailViewController * detail = [[[EventDetailViewController alloc] initWithNibName:@"EventDetailViewController" bundle:nil] autorelease];
    UINavigationController * navVc = [[[UINavigationController alloc] initWithRootViewController:detail] autorelease];
    navVc.navigationBarHidden = YES;
    [ROOT_VC presentModalViewController:navVc animated:YES];

    detail.eventMode = eModeCreateEvent;
    //[detail requestById:236];
}

@end
